<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
    <!-- 现代化导航栏 -->
    <nav class="bg-black/20 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <div class="flex items-center">
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 bg-gradient-to-r from-purple-500 to-pink-500 rounded-lg flex items-center justify-center">
                <Film class="h-6 w-6 text-white" />
              </div>
              <span class="text-xl font-bold bg-gradient-to-r from-white to-purple-200 bg-clip-text text-transparent">
                我的电影网
              </span>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <template v-if="userStore.isAuthenticated">
              <button
                v-if="currentView !== 'home'"
                @click="currentView = 'home'"
                class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 text-white/70 hover:text-white hover:bg-white/10"
              >
                首页
              </button>
              
              <!-- 搜索框 -->
              <div v-if="currentView === 'home'" class="relative">
                <input
                  v-model="searchTerm"
                  type="text"
                  placeholder="搜索电影..."
                  class="w-64 px-4 py-2 pl-10 pr-10 bg-white/10 border border-white/20 rounded-full text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200 text-sm"
                  @keydown.esc="searchTerm = ''"
                  @keydown.enter.prevent=""
                />
                <Film class="h-4 w-4 text-white/50 absolute left-3 top-1/2 transform -translate-y-1/2" />
                <button
                  v-if="searchTerm.trim()"
                  @click="searchTerm = ''"
                  class="absolute right-3 top-1/2 transform -translate-y-1/2 text-white/50 hover:text-white transition-colors duration-200"
                >
                  <span class="text-lg">×</span>
                </button>
              </div>
              
              <button
                @click="currentView = 'add-movie'"
                :class="[
                  'px-4 py-2 rounded-full text-sm font-medium transition-all duration-200',
                  currentView === 'add-movie' 
                    ? 'bg-white/20 text-white shadow-lg' 
                    : 'text-white/70 hover:text-white hover:bg-white/10'
                ]"
              >
                添加电影
              </button>
              
              <button
                @click="currentView = 'my-posts'"
                :class="[
                  'px-4 py-2 rounded-full text-sm font-medium transition-all duration-200',
                  currentView === 'my-posts' 
                    ? 'bg-white/20 text-white shadow-lg' 
                    : 'text-white/70 hover:text-white hover:bg-white/10'
                ]"
              >
                我的发布
              </button>
              
              <a
                href="https://gitee.com/consider-the-line/vue-final-test--movie-website.git"
                target="_blank"
                rel="noopener noreferrer"
                class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 text-white/70 hover:text-white hover:bg-white/10 flex items-center space-x-2"
                title="查看源代码"
              >
                <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.652.242 2.873.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
                </svg>
                <span>源代码</span>
              </a>
              <div class="hidden sm:block text-sm text-white/70">
                欢迎，{{ userStore.user?.realName || userStore.user?.username }}
              </div>
              <button
                @click="logout"
                class="bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600 text-white px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
              >
                退出
              </button>
            </template>
            <template v-else>
              <button
                @click="currentView = 'login'"
                class="text-white/70 hover:text-white px-4 py-2 rounded-full text-sm font-medium transition-all duration-200"
              >
                登录
              </button>
              <button
                @click="currentView = 'register'"
                class="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
              >
                注册
              </button>
            </template>
          </div>
        </div>
      </div>
    </nav>

    <!-- 注册页面 -->
    <div v-if="currentView === 'register'" class="min-h-screen flex items-center justify-center p-4">
      <div class="w-full max-w-md">
        <div class="bg-white/10 backdrop-blur-md rounded-2xl shadow-2xl p-8 border border-white/20">
          <div class="text-center mb-8">
            <div class="w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <UserPlus class="h-8 w-8 text-white" />
            </div>
            <h2 class="text-3xl font-bold text-white mb-2">创建账户</h2>
            <p class="text-white/70">加入我们的电影社区</p>
          </div>
          <form @submit.prevent="register" class="space-y-6">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-white/90 mb-2">用户名</label>
                <input
                  v-model="registerForm.username"
                  type="text"
                  required
                  class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                  placeholder="建议用学号"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-white/90 mb-2">真实姓名</label>
                <input
                  v-model="registerForm.realName"
                  type="text"
                  required
                  class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                  placeholder="请输入真实姓名"
                />
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-white/90 mb-2">密码</label>
              <input
                v-model="registerForm.pwd"
                type="password"
                required
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                placeholder="请输入密码"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-white/90 mb-2">邮箱</label>
              <input
                v-model="registerForm.email"
                type="email"
                required
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                placeholder="请输入邮箱"
              />
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-white/90 mb-2">学号</label>
                <input
                  v-model="registerForm.stuNum"
                  type="text"
                  required
                  class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                  placeholder="学号"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-white/90 mb-2">年龄</label>
                <input
                  v-model="registerForm.age"
                  type="number"
                  class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                  placeholder="年龄"
                />
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-white/90 mb-2">班级</label>
              <input
                v-model="registerForm.className"
                type="text"
                required
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                placeholder="请输入班级"
              />
            </div>
            <button
              type="submit"
              :disabled="isLoading"
              class="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ isLoading ? '注册中...' : '创建账户' }}
            </button>
          </form>
          <div class="mt-6 text-center text-sm text-white/70">
            已有账户？
            <button @click="currentView = 'login'" class="text-purple-300 hover:text-purple-200 font-medium transition-colors duration-200">
              立即登录
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 登录页面 -->
    <div v-if="currentView === 'login'" class="min-h-screen flex items-center justify-center p-4">
      <div class="w-full max-w-md">
        <div class="bg-white/10 backdrop-blur-md rounded-2xl shadow-2xl p-8 border border-white/20">
          <div class="text-center mb-8">
            <div class="w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <LogIn class="h-8 w-8 text-white" />
            </div>
            <h2 class="text-3xl font-bold text-white mb-2">欢迎回来</h2>
            <p class="text-white/70">登录您的电影账户</p>
          </div>
          <form @submit.prevent="login" class="space-y-6">
            <div>
              <label class="block text-sm font-medium text-white/90 mb-2">用户名</label>
              <input
                v-model="loginForm.username"
                type="text"
                required
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                placeholder="请输入用户名"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-white/90 mb-2">密码</label>
              <input
                v-model="loginForm.pwd"
                type="password"
                required
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200"
                placeholder="请输入密码"
              />
            </div>
            <button
              type="submit"
              :disabled="isLoading"
              class="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ isLoading ? '登录中...' : '立即登录' }}
            </button>
          </form>
          <div class="mt-6 text-center text-sm text-white/70">
            还没有账户？
            <button @click="currentView = 'register'" class="text-purple-300 hover:text-purple-200 font-medium transition-colors duration-200">
              立即注册
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主页面（电影列表） -->
    <div v-if="currentView === 'home'" class="min-h-screen">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- 英雄区域 -->
        <div class="text-center mb-12">
          <h1 class="text-4xl md:text-6xl font-bold bg-gradient-to-r from-white via-purple-200 to-pink-200 bg-clip-text text-transparent mb-4">
            发现精彩电影
          </h1>
          <p class="text-xl text-white/70 mb-8 max-w-2xl mx-auto">
            探索最新最热门的电影，与影迷们分享观影体验
          </p>
          

        </div>

        <!-- 搜索结果提示 -->
        <div v-if="searchTerm.trim() && !isLoading" class="mb-8">
          <div class="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-white/10">
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-3">
                <Film class="h-5 w-5 text-purple-300" />
                <span class="text-white">
                  搜索 "<span class="text-purple-300 font-medium">{{ searchTerm }}</span>" 
                  找到 <span class="text-purple-300 font-medium">{{ filteredMovies.length }}</span> 部电影
                </span>
              </div>
              <button
                @click="searchTerm = ''"
                class="text-white/50 hover:text-white transition-colors duration-200"
              >
                <span class="text-sm">清除搜索</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoading" class="text-center py-20">
          <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full mb-4">
            <div class="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
          </div>
          <p class="text-white/70 text-lg">正在加载精彩内容...</p>
        </div>

        <!-- 电影网格 -->
        <div v-else class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-6">
          <div
            v-for="movie in filteredMovies"
            :key="movie.id"
            class="group cursor-pointer transform transition-all duration-300 hover:scale-105"
            @click="viewMovieDetail(movie.id)"
          >
            <div class="bg-white/10 backdrop-blur-md rounded-2xl overflow-hidden shadow-xl border border-white/20 hover:shadow-2xl hover:border-white/30 transition-all duration-300">
              <div class="aspect-[2/3] relative overflow-hidden">
                <img 
                  :src="movie.poster || '/placeholder.svg?height=450&width=300'" 
                  :alt="movie.title" 
                  class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" 
                />
                <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                <div class="absolute bottom-4 left-4 right-4 transform translate-y-4 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-300">
                  <div class="flex items-center justify-between text-white">
                    <div class="flex items-center space-x-1">
                      <Star class="h-4 w-4 text-yellow-400 fill-current" />
                      <span class="text-sm font-medium">{{ movie.rating || 'N/A' }}</span>
                    </div>
                    <Play class="h-6 w-6" />
                  </div>
                </div>
              </div>
              <div class="p-4">
                <h3 class="text-white font-semibold text-lg mb-2 line-clamp-1">{{ movie.title }}</h3>
                <p class="text-white/70 text-sm line-clamp-2 mb-3">{{ movie.description }}</p>
                <div class="flex items-center justify-between text-xs">
                  <span class="text-white/50">{{ movie.authorName }}</span>
                  <span class="text-purple-300">{{ movie.year || '未知' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!isLoading && filteredMovies.length === 0" class="text-center py-20">
          <div class="w-24 h-24 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-6">
            <Film class="h-12 w-12 text-white/50" />
          </div>
          <h3 class="text-2xl font-semibold text-white mb-2">
            {{ searchTerm.trim() ? '未找到匹配的电影' : '暂无电影' }}
          </h3>
          <p class="text-white/70 mb-8">
            {{ searchTerm.trim() 
              ? '没有找到匹配的电影，试试其他关键词吧' 
              : '还没有电影，快来添加第一部电影吧！' 
            }}
          </p>
          <div class="flex flex-col sm:flex-row items-center justify-center gap-4">
            <button
              v-if="searchTerm.trim()"
              @click="searchTerm = ''"
              class="bg-gradient-to-r from-gray-500 to-gray-600 hover:from-gray-600 hover:to-gray-700 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              清除搜索
            </button>
            <button
              v-if="userStore.isAuthenticated"
              @click="currentView = 'add-movie'"
              class="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              {{ searchTerm.trim() ? '添加电影' : '添加第一部电影' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 电影详情页面 -->
    <div v-if="currentView === 'movie-detail'" class="min-h-screen">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <button
          @click="currentView = 'home'"
          class="inline-flex items-center px-4 py-2 text-white/70 hover:text-white bg-white/10 hover:bg-white/20 border border-white/20 rounded-xl transition-all duration-200 mb-8 backdrop-blur-sm"
        >
          <ArrowLeft class="h-4 w-4 mr-2" />
          返回首页
        </button>

        <div v-if="selectedMovie" class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-12">
          <!-- 电影海报 -->
          <div class="lg:col-span-1">
            <div class="aspect-[2/3] relative rounded-2xl overflow-hidden shadow-2xl">
              <img 
                :src="selectedMovie.poster || '/placeholder.svg?height=600&width=400'" 
                :alt="selectedMovie.title" 
                class="w-full h-full object-cover" 
              />
            </div>
          </div>

          <!-- 电影信息 -->
          <div class="lg:col-span-2">
            <div class="bg-white/10 backdrop-blur-md rounded-2xl shadow-xl p-8 border border-white/20">
              <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between mb-6">
                <div class="flex-1">
                  <h1 class="text-3xl md:text-4xl font-bold text-white mb-4">{{ selectedMovie.title }}</h1>
                  <div class="flex flex-wrap items-center gap-4 mb-6 text-white/70">
                    <div class="flex items-center space-x-2">
                      <Calendar class="h-4 w-4" />
                      <span>{{ selectedMovie.year || '年份未知' }}</span>
                    </div>
                    <div class="flex items-center space-x-2">
                      <User class="h-4 w-4" />
                      <span>{{ selectedMovie.authorName }}</span>
                    </div>
                  </div>
                </div>
                <div class="flex items-center bg-gradient-to-r from-yellow-400 to-orange-400 text-black px-4 py-2 rounded-xl font-bold text-lg">
                  <Star class="h-5 w-5 mr-1 fill-current" />
                  {{ selectedMovie.rating || 'N/A' }}
                </div>
              </div>
              
              <div class="space-y-6">
                <div>
                  <h3 class="text-xl font-semibold text-white mb-3">剧情简介</h3>
                  <p class="text-white/80 leading-relaxed">{{ selectedMovie.description }}</p>
                </div>
                <div v-if="selectedMovie.cast" class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <h3 class="text-lg font-semibold text-white mb-2">主演</h3>
                    <p class="text-white/70">{{ selectedMovie.cast }}</p>
                  </div>
                </div>
                <div v-if="selectedMovie.playUrl">
                  <a 
                    :href="selectedMovie.playUrl" 
                    target="_blank" 
                    class="inline-flex items-center bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl mr-4"
                  >
                    <Play class="h-5 w-5 mr-2" />
                    立即观看
                  </a>
                  <!-- 编辑按钮，只有电影上传者才能看到 -->
                  <!-- 暂时禁用编辑功能，因为后端不支持完整的电影信息更新 -->
                  <!--
                  <button
                    v-if="userStore.isAuthenticated && selectedMovie.userid === userStore.user?.id"
                    @click="editMovie(selectedMovie)"
                    class="inline-flex items-center bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
                  >
                    <Edit class="h-5 w-5 mr-2" />
                    编辑电影
                  </button>
                  -->
                </div>
                <!-- 没有播放链接时也可能需要编辑按钮 -->
                <!-- 暂时禁用编辑功能，因为后端不支持完整的电影信息更新 -->
                <!--
                <div v-else-if="userStore.isAuthenticated && selectedMovie.userid === userStore.user?.id">
                  <button
                    @click="editMovie(selectedMovie)"
                    class="inline-flex items-center bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
                  >
                    <Edit class="h-5 w-5 mr-2" />
                    编辑电影
                  </button>
                </div>
                -->
              </div>
            </div>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="bg-white/10 backdrop-blur-md rounded-2xl shadow-xl p-8 border border-white/20">
          <h2 class="text-2xl font-bold text-white mb-8 flex items-center">
            <MessageCircle class="h-6 w-6 mr-3" />
            评论区 ({{ movieComments.length }})
          </h2>

          <!-- 添加评论 -->
          <div v-if="userStore.isAuthenticated" class="mb-8">
            <form @submit.prevent="addComment" class="space-y-6">
              <!-- 暂时隐藏评分功能，因为数据库不支持评分存储 -->
              <!-- 
              <div>
                <label class="block text-sm font-medium text-white/90 mb-3">您的评分</label>
                <div class="flex items-center space-x-2">
                  <button
                    v-for="rating in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
                    :key="rating"
                    type="button"
                    @click="newCommentRating = rating"
                    :class="[
                      'w-10 h-10 rounded-full text-sm font-bold transition-all duration-200',
                      rating <= newCommentRating 
                        ? 'bg-gradient-to-r from-yellow-400 to-orange-400 text-black shadow-lg' 
                        : 'bg-white/10 text-white/70 hover:bg-white/20'
                    ]"
                  >
                    {{ rating }}
                  </button>
                </div>
              </div>
              -->
              <textarea
                v-model="newCommentContent"
                placeholder="分享您的观影感受..."
                rows="4"
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm transition-all duration-200 resize-none"
              ></textarea>
              <button
                type="submit"
                class="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
              >
                发表评论
              </button>
            </form>
          </div>

          <div v-else class="mb-8 p-6 bg-white/5 rounded-xl text-center border border-white/10">
            <p class="text-white/70 mb-4">登录后即可发表评论</p>
            <button
              @click="currentView = 'login'"
              class="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              立即登录
            </button>
          </div>

          <!-- 评论列表 -->
          <div class="space-y-6">
            <div v-for="comment in movieComments" :key="comment.id" class="bg-white/5 rounded-xl p-6 border border-white/10">
              <div class="flex items-start space-x-4">
                <div class="w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center text-white font-bold text-lg">
                  {{ (comment.authorName || comment.realName || comment.username || 'U')[0]?.toUpperCase() }}
                </div>
                <div class="flex-1">
                  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3">
                    <div class="flex items-center space-x-3 mb-2 sm:mb-0">
                      <span class="font-semibold text-white">{{ comment.authorName || comment.realName || comment.username || '匿名用户' }}</span>
                      <!-- 暂时隐藏评分显示，因为数据库不支持评分存储 -->
                      <!-- 
                      <div class="flex items-center bg-gradient-to-r from-yellow-400 to-orange-400 text-black px-2 py-1 rounded-lg text-sm font-bold">
                        <Star class="h-3 w-3 mr-1 fill-current" />
                        {{ comment.rating || 5 }}
                      </div>
                      -->
                    </div>
                    <span class="text-white/50 text-sm">{{ formatDate(comment.addedTime) }}</span>
                  </div>
                  <p class="text-white/80 leading-relaxed">{{ comment.body || comment.content || '暂无评论内容' }}</p>
                </div>
              </div>
            </div>
            
            <div v-if="movieComments.length === 0" class="text-center py-12">
              <div class="w-16 h-16 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-4">
                <MessageCircle class="h-8 w-8 text-white/50" />
              </div>
              <p class="text-white/50 text-lg">暂无评论</p>
              <p class="text-white/30 text-sm mt-2">成为第一个评论的人吧！</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加电影页面 -->
    <div v-else-if="currentView === 'add-movie'" class="p-6 lg:p-8">
      <button
        @click="currentView = 'home'"
        class="mb-6 flex items-center text-purple-300 hover:text-white transition-colors duration-200"
      >
        <ChevronLeft class="h-5 w-5 mr-2" />
        返回首页
      </button>
      
      <div class="max-w-2xl mx-auto">
        <h2 class="text-3xl font-bold text-white mb-8 text-center">添加新电影</h2>
        
        <form @submit.prevent="addMovie" class="space-y-6">
          <div>
            <label class="block text-white/70 font-medium mb-2">电影标题</label>
            <input
              v-model="newMovie.title"
              type="text"
              required
              class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm"
              placeholder="请输入电影标题"
            />
          </div>
          
          <div>
            <label class="block text-white/70 font-medium mb-2">电影简介</label>
            <textarea
              v-model="newMovie.description"
              rows="4"
              required
              class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm resize-none"
              placeholder="请输入电影简介"
            ></textarea>
          </div>
          
          <div>
            <label class="block text-white/70 font-medium mb-2">演员</label>
            <input
              v-model="newMovie.actor"
              type="text"
              required
              class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm"
              placeholder="请输入主要演员"
            />
          </div>
          
          <div>
            <label class="block text-white/70 font-medium mb-2">电影海报链接</label>
            <input
              v-model="newMovie.image"
              type="url"
              required
              class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent backdrop-blur-sm"
              placeholder="请输入电影海报图片链接"
            />
          </div>
          
          <button
            type="submit"
            :disabled="isLoading"
            class="w-full py-3 bg-gradient-to-r from-purple-600 to-pink-600 text-white font-semibold rounded-lg hover:from-purple-700 hover:to-pink-700 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg"
          >
            {{ isLoading ? '添加中...' : '添加电影' }}
          </button>
        </form>
      </div>
    </div>

    <!-- 我的发布页面 -->
    <div v-else-if="currentView === 'my-posts'" class="p-6 lg:p-8">
      <button
        @click="currentView = 'home'"
        class="mb-6 flex items-center text-purple-300 hover:text-white transition-colors duration-200"
      >
        <ChevronLeft class="h-5 w-5 mr-2" />
        返回首页
      </button>
      
      <div class="max-w-6xl mx-auto">
        <h2 class="text-3xl font-bold text-white mb-8 text-center">我的发布</h2>
        
        <div v-if="isLoadingMyPosts" class="text-center py-20">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
          <p class="text-white/70 mt-4">加载中...</p>
        </div>
        
        <div v-else class="space-y-8">
          <!-- 我发布的电影 -->
          <div>
            <h3 class="text-2xl font-semibold text-white mb-6 flex items-center">
              <Film class="h-6 w-6 mr-2 text-purple-400" />
              我发布的电影 ({{ myMovies.length }})
            </h3>
            
            <div v-if="myMovies.length === 0" class="text-center py-12 bg-white/5 rounded-xl border border-white/10">
              <Film class="h-16 w-16 text-white/30 mx-auto mb-4" />
              <p class="text-white/70 text-lg">还没有发布过电影</p>
              <button
                @click="currentView = 'add-movie'"
                class="mt-4 px-6 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg hover:from-purple-700 hover:to-pink-700 transition-all duration-200"
              >
                发布第一部电影
              </button>
            </div>
            
            <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              <div
                v-for="movie in myMovies"
                :key="movie.id"
                class="bg-white/10 backdrop-blur-sm rounded-xl overflow-hidden border border-white/20 hover:border-purple-400/50 transition-all duration-300 hover:scale-105 hover:shadow-2xl cursor-pointer"
                @click="viewMovieDetail(movie)"
              >
                <div class="aspect-[2/3] overflow-hidden">
                  <img
                    :src="movie.image"
                    :alt="movie.title"
                    class="w-full h-full object-cover transition-transform duration-300 hover:scale-110"
                    @error="$event.target.src = '/placeholder.jpg'"
                  />
                </div>
                <div class="p-4">
                  <h3 class="font-semibold text-white mb-2 line-clamp-1">{{ movie.title }}</h3>
                  <p class="text-white/70 text-sm line-clamp-2 mb-3">{{ movie.description }}</p>
                  <div class="text-xs text-white/50">
                    发布于 {{ new Date(movie.createtime).toLocaleDateString() }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 我发表的评论 -->
          <div>
            <h3 class="text-2xl font-semibold text-white mb-6 flex items-center">
              <MessageSquare class="h-6 w-6 mr-2 text-purple-400" />
              我发表的评论 ({{ myComments.length }})
            </h3>
            
            <div v-if="myComments.length === 0" class="text-center py-12 bg-white/5 rounded-xl border border-white/10">
              <MessageSquare class="h-16 w-16 text-white/30 mx-auto mb-4" />
              <p class="text-white/70 text-lg">还没有发表过评论</p>
              <button
                @click="currentView = 'home'"
                class="mt-4 px-6 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg hover:from-purple-700 hover:to-pink-700 transition-all duration-200"
              >
                去看看电影
              </button>
            </div>
            
            <div v-else class="space-y-4">
              <div
                v-for="comment in myComments"
                :key="comment.id"
                class="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20 hover:border-purple-400/50 transition-all duration-300"
              >
                <div class="flex justify-between items-start mb-3">
                  <div class="text-sm text-white/70">
                    评论于电影 ID: {{ comment.articleid }}
                  </div>
                  <div class="text-xs text-white/50">
                    {{ new Date(comment.createtime).toLocaleString() }}
                  </div>
                </div>
                <p class="text-white leading-relaxed">{{ comment.content }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { 
  Film, UserPlus, LogIn, Star, Play, ArrowLeft, Calendar, 
  User, MessageCircle, Plus, Edit, ChevronLeft, MessageSquare
} from 'lucide-vue-next'
import { useUserStore } from '../stores/user'
import { 
  registerUser, 
  loginUser, 
  getMovieList, 
  addMovie,
  updateMovie,
  getMovieComments,
  addMovieComment
} from '../utils/movieApi'

// 用户状态管理
const userStore = useUserStore()

// 响应式数据
const currentView = ref('home')
const searchTerm = ref('')
const isLoading = ref(false)
const movies = ref([])
const selectedMovieId = ref(null)
const isEditingMovie = ref(false)
const editingMovieId = ref(null)

// 我的发布页面数据
const myMovies = ref([]) // 我发布的电影
const myComments = ref([]) // 我发表的评论
const isLoadingMyPosts = ref(false)

// 评论相关 - 使用API数据而不是硬编码
const newCommentContent = ref('')
const newCommentRating = ref(5)
const comments = ref([]) // 存储从API加载的评论数据

// 表单数据
const registerForm = ref({
  username: '',
  pwd: '',
  realName: '',
  email: '',
  stuNum: '',
  className: '',
  age: ''
})

const loginForm = ref({
  username: '20005668',
  pwd: '123456'
})

const movieForm = ref({
  title: '',
  description: '',
  year: '',
  cast: '',
  poster: '',
  playUrl: ''
})

// 计算属性
const filteredMovies = computed(() => {
  if (!searchTerm.value || !searchTerm.value.trim()) {
    return movies.value || []
  }
  
  const searchLower = searchTerm.value.toLowerCase()
  return (movies.value || []).filter(movie => {
    if (!movie) return false
    
    const title = (movie.title || '').toString().toLowerCase()
    const description = (movie.description || '').toString().toLowerCase()
    const cast = (movie.cast || '').toString().toLowerCase()
    const authorName = (movie.authorName || '').toString().toLowerCase()
    
    return (
      title.includes(searchLower) ||
      description.includes(searchLower) ||
      cast.includes(searchLower) ||
      authorName.includes(searchLower)
    )
  })
})

const selectedMovie = computed(() => {
  return movies.value.find(movie => movie.id == selectedMovieId.value)
})

const movieComments = computed(() => {
  return comments.value // 直接使用API加载的评论数据
})

// 方法
const register = async () => {
  isLoading.value = true
  try {
    const result = await registerUser(registerForm.value)
    if (result) {
      currentView.value = 'login'
      registerForm.value = { username: '', pwd: '', realName: '', email: '', stuNum: '', className: '', age: '' }
    } else {
      alert('注册失败，请检查信息是否正确')
    }
  } catch (error) {
    alert('注册失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const login = async () => {
  isLoading.value = true
  try {
    const result = await loginUser(loginForm.value)
    if (result) {
      userStore.setUser(result)
      currentView.value = 'home'
      loginForm.value = { username: '20005668', pwd: '123456' }
      await loadMovies()
    } else {
      alert('登录失败，请检查用户名和密码')
    }
  } catch (error) {
    alert('登录失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const logout = () => {
  userStore.logout()
  currentView.value = 'home'
}

const loadMovies = async () => {
  isLoading.value = true
  try {
    const movieList = await getMovieList()
    movies.value = movieList.reverse() // 让最新的电影排在前面
  } catch (error) {
    console.error('加载电影列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

const viewMovieDetail = async (movieId) => {
  selectedMovieId.value = movieId
  currentView.value = 'movie-detail'
  // 加载该电影的评论
  await loadMovieComments(movieId)
}

// 加载电影评论
const loadMovieComments = async (movieId) => {
  try {
    const movieComments = await getMovieComments(movieId.toString())
    console.log('加载的评论数据:', movieComments) // 调试用
    
    // 按时间倒序排列，最新评论在前
    if (movieComments && movieComments.length > 0) {
      const sortedComments = movieComments.sort((a, b) => {
        const timeA = new Date(a.addedTime).getTime()
        const timeB = new Date(b.addedTime).getTime()
        return timeB - timeA // 倒序：最新的在前
      })
      comments.value = sortedComments
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    comments.value = []
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } catch (e) {
    return '未知时间'
  }
}

// 添加评论 - 使用API
const addComment = async () => {
  if (!newCommentContent.value.trim()) return
  
  try {
    const commentData = {
      content: newCommentContent.value
    }
    
    const result = await addMovieComment(selectedMovieId.value.toString(), commentData)
    if (result) {
      // 评论添加成功，重新加载评论列表
      await loadMovieComments(selectedMovieId.value)
      newCommentContent.value = ''
    } else {
      alert('评论发表失败，请稍后重试')
    }
  } catch (error) {
    alert('评论发表失败，请稍后重试')
    console.error('添加评论失败:', error)
  }
}

const addNewMovie = async () => {
  if (!movieForm.value.title || !movieForm.value.description) {
    alert('请填写必填字段')
    return
  }
  
  isLoading.value = true
  try {
    const result = await addMovie(movieForm.value)
    if (result) {
      currentView.value = 'home'
      movieForm.value = { title: '', description: '', year: '', cast: '', poster: '', playUrl: '' }
      // 重置编辑状态
      isEditingMovie.value = false
      editingMovieId.value = null
      await loadMovies() // 重新加载，新电影会排在前面
    } else {
      alert('添加电影失败，请稍后重试')
    }
  } catch (error) {
    alert('添加电影失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 更新电影
const updateExistingMovie = async () => {
  if (!movieForm.value.title || !movieForm.value.description) {
    alert('请填写必填字段')
    return
  }
  
  isLoading.value = true
  try {
    const result = await updateMovie(editingMovieId.value.toString(), movieForm.value)
    if (result) {
      currentView.value = 'home'
      movieForm.value = { title: '', description: '', year: '', cast: '', poster: '', playUrl: '' }
      isEditingMovie.value = false
      editingMovieId.value = null
      await loadMovies() // 重新加载更新后的电影列表
    } else {
      alert('更新电影失败，请稍后重试')
    }
  } catch (error) {
    alert('更新电影失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const editMovie = (movie) => {
  // 暂时禁用编辑功能，因为后端不支持完整的电影信息更新
  alert('编辑功能暂时不可用，后端只支持编辑标题，暂不支持编辑完整的电影信息。')
  return
  
  // 设置编辑状态
  isEditingMovie.value = true
  editingMovieId.value = movie.id
  currentView.value = 'edit-movie'
  
  // 用现有电影数据填充表单
  movieForm.value = {
    title: movie.title || '',
    description: movie.description || '',
    year: movie.year || '',
    cast: Array.isArray(movie.cast) ? movie.cast.join(', ') : (movie.cast || ''),
    poster: movie.poster || '',
    playUrl: movie.playUrl || ''
  }
}

// 加载用户发布的内容
const loadMyPosts = async () => {
  if (!userStore.isAuthenticated) return
  
  isLoadingMyPosts.value = true
  try {
    // 获取我发布的电影
    const moviesResponse = await getMovies()
    myMovies.value = moviesResponse.data.filter(movie => 
      movie.userid === userStore.user?.id
    ).reverse() // 最新的在前面
    
    // 获取我发表的评论 - 直接调用getList获取所有评论
    const { getList } = await import('../utils/request')
    const COMMENT_TYPE_INDEX = 4
    const allComments = await getList(COMMENT_TYPE_INDEX)
    myComments.value = (allComments || []).filter(comment => 
      comment.userid === userStore.user?.id
    ).reverse() // 最新的在前面
    
  } catch (error) {
    console.error('加载我的发布失败:', error)
  } finally {
    isLoadingMyPosts.value = false
  }
}

// 生命周期
onMounted(async () => {
  // 恢复用户登录状态
  userStore.restoreUser()
  await loadMovies()
})

// 观察 currentView 变化，当切换到我的发布页面时自动加载数据
watch(currentView, (newView) => {
  if (newView === 'my-posts') {
    loadMyPosts()
  }
})
</script>

<style scoped>
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>